package tcp;


import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/*
* 实现TCP网络编程
* 例子1:客户端发送信息给服务端,服务端将信息显示在服务台上
*
*
* */
public class TcpTest1 {

    //客户端
    @Test
    public void client() throws IOException {

        Socket socket = null;
        OutputStream os = null;
        try {
            //1:创建Socket对象,指明服务器端的IP和端口号
            InetAddress ip = InetAddress.getByName("localhost");
            socket = new Socket(ip,8889);

            //2:获取一个输出流,用于输出数据
            os = socket.getOutputStream();
            os.write("你好我是客户端".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null)
                os.close();
            if (socket != null)
                socket.close();
        }
    }

    @Test
    public void server(){
        ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //1:创建服务器端的ServerSocket,指明自己的接收数据的端口
            ss = new ServerSocket(8889);
            //2:接收来自于客户端的socket
            socket = ss.accept();
            //3:获取输入流
            is = socket.getInputStream();

//        不建议这样写
//        byte[] bytes = new byte[20];
//        int len;
//        while ((len = is.read(bytes)) != -1) {
//            String s = new String(bytes, 0, len);
//            System.out.println(s);
//        }

            //4:读取输入流的数据
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[5];
            int len;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());
            System.out.println("收到来自于:" + socket.getInetAddress() + "的数据");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5:关闭资源
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
